package com.yds.bluetooth

import android.bluetooth.*
import android.content.Context
import android.util.Log
import androidx.fragment.app.FragmentActivity
import java.util.*

/**
 * 连接低功耗蓝牙
 */
@Suppress("Unused")
object ConnectBleDeviceManager {
    private const val TAG = "YDS蓝牙"

    // 服务uuid
    private var mServiceUuid = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"

    // 写入特征值uuid
    private var mCharacterWriteUuid = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"

    // 通知特征值uuid
    private var mCharacterNotifyUuid = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"

    // 连接蓝牙设备结果回调
    private var connectResultCallback: ((Boolean) -> Unit)? = null

    fun initUuid(serviceUuid: String, characterWriteUuid: String, characterNotifyUuid: String) {
        this.mServiceUuid = serviceUuid
        this.mCharacterWriteUuid = characterWriteUuid
        this.mCharacterNotifyUuid = characterNotifyUuid
    }

    /**
     * 连接回调
     */
    private val gattCallback = object : BluetoothGattCallback() {
        override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                Log.i(TAG, "连接成功")
                gatt?.discoverServices()
                connectResultCallback?.invoke(true)
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                Log.i(TAG, "连接断开")
                connectResultCallback?.invoke(false)
            }
        }

        override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.i(TAG, "服务发现完成")
                val services = gatt?.services
                services?.forEach {
//                    Log.i(Tag, "服务 UUID: ${it.uuid}")
                    val characteristics = it?.characteristics
                    characteristics?.forEach { characteristic ->
//                        Log.i(Tag, "特征 -- UUID: ${characteristic.uuid}")
                        val properties = characteristic.properties
                        if (properties and BluetoothGattCharacteristic.PROPERTY_NOTIFY != 0) {
                            // 该特征值支持通知功能
                            if (characteristic.uuid == UUID.fromString(mCharacterNotifyUuid)) {
                                setNotification(gatt, characteristic)
                            }
                        }
                    }
                }
            }
        }

        override fun onCharacteristicRead(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?, status: Int) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.i(TAG, "读取的特征值成功")
                val data = characteristic?.value
                data?.let { receiveResultCallback?.invoke(it) }
            }
        }

        override fun onCharacteristicWrite(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?, status: Int) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.i(TAG, "写入特征值成功")
                sendResultCallback?.invoke(true)
            } else {
                sendResultCallback?.invoke(false)
            }
        }

        override fun onCharacteristicChanged(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?) {
            super.onCharacteristicChanged(gatt, characteristic)
            // 此方法会在特征值发生变化时调用，也就是接收到新数据时
            Log.i(TAG, "onCharacteristicChanged")
            val data = characteristic?.value
            data?.let { receiveResultCallback?.invoke(it) }
        }
    }

    /**
     * 设置通知接收回传消息
     */
    private fun setNotification(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?) {
        if (gatt == null || characteristic == null) return
        // 启用通知功能
        gatt.setCharacteristicNotification(characteristic, true)
        // 获取特征值的描述符\
        val descriptors = characteristic.descriptors
        descriptors.forEach {
            if (it != null) {
//                Log.i(Tag, "设置通知接收回传消息" + it.uuid)
                it.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
                gatt.writeDescriptor(it)
            }
        }
    }

    private var bluetoothGatt: BluetoothGatt? = null

    /**
     * 连接到BLE设备
     */
    fun connectToDevice(context: Context, device: BluetoothDevice, resultCallback: (Boolean) -> Unit) {
        this.connectResultCallback = resultCallback

        bluetoothGatt = device.connectGatt(context, false, gattCallback)
    }

    // 蓝牙设备发送数据结果回调
    private var sendResultCallback: ((Boolean) -> Unit)? = null

    // 蓝牙设备返回数据结果回调
    private var receiveResultCallback: ((ByteArray) -> Unit)? = null

    /**
     * 发送数据到BLE设备
     */
    fun sendDataToBleDevice(data: ByteArray, sendResultCallback: (Boolean) -> Unit, receiveResultCallback: (ByteArray) -> Unit) {
        this.sendResultCallback = sendResultCallback
        this.receiveResultCallback = receiveResultCallback
        bluetoothGatt?.let { gatt ->
            val service = gatt.getService(UUID.fromString(mServiceUuid))
            val characteristic = service?.getCharacteristic(UUID.fromString(mCharacterWriteUuid))
            characteristic?.let {
                it.value = data
                gatt.writeCharacteristic(it)
            }
        }
    }

    /**
     * 断开与BLE设备的连接
     */
    fun disconnectFromDevice() {
        bluetoothGatt?.disconnect()
        bluetoothGatt?.close()
    }
}